﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Services.Util;
using Model.Util;
using Xproject.Util;

namespace WeiXinpProAdmin.Controllers
{
    public class UtilController : AdminBaseController
    {
        UploadFileServices m_UploadFileServices;
        public UtilController(UploadFileServices mUploadFileServices)
        {
            m_UploadFileServices = mUploadFileServices;
        }
        
        // GET: Util
        public ActionResult Index()
        {
            return View();
        }

        public JsonResult UploadFiles()
        {
            var jsonData = new Object();
            string result = string.Empty;
            bool success = false;
            string Virbase = @"Upload\Images\";
            string DataTimeFolder = DateTime.Now.ToString("yyyyMMdd");
            string localpath = AppDomain.CurrentDomain.BaseDirectory + Virbase;                      
            string Folder = localpath + DataTimeFolder;
             
            if (!Directory.Exists(Folder))
                Directory.CreateDirectory(Folder);
            UploadFile uf = new UploadFile();
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            if (files.Count == 0)
            {
                jsonData = new { Success = false, Data = uf };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
            HttpPostedFile file = files[0];
            
            string batchId = System.Web.HttpContext.Current.Request["batchId"];
            int index = Cache_ComUtil.GetBatchCount(batchId);


            uf.FileName = file.FileName;
            uf.FileExt = Path.GetExtension(file.FileName);
            uf.FileSize = file.ContentLength;
            uf.Site = Site;
            uf.ServiceAddress = CommonHelper.GetAppSettings("Domain");
            string guidName = Guid.NewGuid().ToString() + uf.FileExt;
            uf.Path = ("\\"+ Virbase + DataTimeFolder+"\\" + guidName).Replace("\\","/");
            uf.FileId = Guid.NewGuid().ToString();
            uf.Spec = index.ToString();

            string LocalFullPath = Folder + @"\" + guidName;
            uf.LocalFullPath = LocalFullPath;
            file.SaveAs(LocalFullPath);                        
            success = m_UploadFileServices.AdduUploadFile(uf, this.CurrentUser.UserID.ToString());
            if (success)
            {
                index++;
                Cache_ComUtil.SetBatchCount(batchId, index);
            }
            jsonData = new { Success = success, Data = uf.FileId };
            return Json(jsonData, JsonRequestBehavior.AllowGet);

        }
    }
}